import { defineStore } from 'pinia'

/**
 * 用户状态管理仓库
 * 
 * @description 管理用户相关信息，包括认证token等
 */
export const useUserStore = defineStore('user', {
  state: () => ({
    /**
     * 用户认证token
     * @type {string | null}
     */
    token: localStorage.getItem('token') || null,
    
    /**
     * 用户名
     * @type {string | null}
     */
    username: localStorage.getItem('username') || null,
  }),
  
  getters: {
    /**
     * 检查用户是否已认证
     * @returns {boolean} 是否已认证
     */
    isAuthenticated: (state) => !!state.token,
    
    /**
     * 获取当前token
     * @returns {string | null} 当前token
     */
    getToken: (state) => state.token,
    
    /**
     * 获取当前用户名
     * @returns {string | null} 当前用户名
     */
    getUsername: (state) => state.username,
  },
  
  actions: {
    /**
     * 设置用户token
     * 
     * @param {string} token - 用户认证token
     * @param {string} [username] - 用户名（可选）
     * @returns {void}
     */
    setToken(token: string, username?: string) {
      this.token = token
      // 保存到localStorage
      localStorage.setItem('token', token)
      
      if (username) {
        this.username = username
        localStorage.setItem('username', username)
      }
    },
    
    /**
     * 清除用户认证信息
     * 
     * @returns {void}
     */
    clearAuth() {
      this.token = null
      this.username = null
      // 从localStorage中移除
      localStorage.removeItem('token')
      localStorage.removeItem('username')
    },
    
    /**
     * 从localStorage更新用户信息
     * 
     * @returns {void}
     */
    updateFromLocalStorage() {
      this.token = localStorage.getItem('token') || null
      this.username = localStorage.getItem('username') || null
    }
  },
})

/**
 * 用户状态管理仓库实例
 */
export default useUserStore